/*
 * Author: xiguan
 * Mail: xiguan.teng@qq.com
 * -----
 * Last Modified: 2022-05-27 14:27:39
 * Modified By: xiguan
 * -----
 * Copyright (c) 2022 XiGuan Inc.
 * 
 * No Bug No error No warning.
 */



#include <bits/stdc++.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>


using namespace std;

void message_err(const char *msg){
    perror(msg);
    exit(1);
}

/**
 * @brief 自己的读取函数
 * 
 * @param fd 
 * @return int 
 */
int read_my(int fd);


int main(int argc, char *argv[]){

    int fd1;

    if(argc < 2){
        printf("Usage: %s <file>\n", argv[0]);
        exit(1);
    }

    if((fd1 = open(argv[1], O_RDWR, S_IRWXU)) == -1){
        message_err("open");
    }

    read_my(fd1);

    return 0;
}

int read_my(int fd){
    int res = 0;
    int ret;
    char buf[1024] = {0};
    int len;
    // 计算文件长度
    if((lseek(fd, 0, SEEK_END)) == -1){
        message_err("lseek end");
    }
    if((len = lseek(fd, 0, SEEK_CUR)) == -1){
        message_err("lseek cur");
    }
    if((lseek(fd, 0, SEEK_SET)) == -1){
        message_err("lseek set");
    }


    while((ret = read(fd, buf, 10)) >= 0){
        if(ret == 0){
            cout << "读取完 退出" << endl;
            break;
        }
        for(int i = 0; i < ret; ++ i){
            cout << buf[i];
        }
        res += ret;
    }

    if(res == len){
        cout << endl << endl << "读取完毕" << endl;
    } else{
        cout << endl << endl << "读取未完毕" << endl;
    }

    return res;
}

